package com.shanyue.redwine.utils;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.shanyue.redwine.R;
import com.shanyue.redwine.receiver.TagAliasOperatorHelper;

import java.io.File;

/**
 * 项目：HongJiu  包名：com.shanyue.redwine.utils
 * <p>
 * huangxiaoyu
 * <p>
 * 2018/7/20
 * <p>
 * desc
 */
public class Utils {
    public static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }


    /**
     * 打电话
     *
     * @param context
     * @param phone   电话号码
     */
    public static void telTo(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) !=
                PackageManager.PERMISSION_GRANTED) {
            showToast(context, "未获得权限,呼叫失败");
            return;
        }
        context.startActivity(intent);
    }

    /**
     * 发短信
     *
     * @param context
     * @param phone      短信接收者
     * @param defaultMsg 短信内容
     */
    public static void sendSms(Context context, String phone, String defaultMsg) {
        Uri uri = Uri.parse("smsto:" + phone);
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
        if (!TextUtils.isEmpty(defaultMsg)) {
            intent.putExtra("sms_body", defaultMsg);
        }
        context.startActivity(intent);
    }

    /**
     * 分享 系统分享
     *
     * @param context
     * @param shareStr 分享内容
     */
    public static void share(Context context, String shareStr) {
        Intent intent = new Intent(Intent.ACTION_SEND); // 启动分享发送的属性
        intent.setType("text/plain"); // 分享发送的数据类型
        intent.putExtra(Intent.EXTRA_TEXT, shareStr); // 分享的内容
        context.startActivity(Intent.createChooser(intent, "分享到"));// 目标应用选择对话框的标题
    }

    /**
     * sharesdk 分享
     *
     * @param context
     * @param title
     * @param titleUrl
     * @param msg
     * @param localImgPaht
     * @param imgUrl
     * @param url
     * @param comment
     * @param siteUrl
     * @param callBackListener
     */
    public static void showShare(Context context, String title, String titleUrl, String msg,
                                 String localImgPaht, String imgUrl, String url, String comment,
                                 String siteUrl, PlatformActionListener callBackListener) {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle(title);
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl(titleUrl);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(msg);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        if (!TextUtils.isEmpty(localImgPaht)) {
            oks.setImagePath(localImgPaht);//确保SDcard下面存在此张图片
        } else {
            oks.setImageUrl(imgUrl);
        }
        oks.setUrl(url);
        // url在微信、微博，Facebook等平台中使用
        // comment是我对这条分享的评论，仅在人人网使用
        oks.setComment(comment);
        oks.setCallback(callBackListener);
        oks.setSite(context.getString(R.string.app_name));
        oks.setSiteUrl(context.getString(R.string.app_down_page));
        if (!TextUtils.isEmpty(siteUrl)) {
            oks.setSiteUrl(siteUrl);
        }
        // 启动分享GUI
        oks.show(context);
    }

    public static void appShare(Context context, String shareStr) {
        JSONObject object = JSON.parseObject(shareStr);
        try {
            showShare(context, object.getString("title"), object.getString("url"), object
                            .getString("msg"), null, object.getString("imgUrl"), object.getString("url"),
                    "", context.getString(R.string.app_down_page), null);
        } catch (Exception ex) {
            ex.printStackTrace();
            SweetAlertDialogFactory.build(context, SweetAlertDialog.ERROR_TYPE).setContentText(ex
                    .getMessage()).show();
        }
    }

    public static void loadImg(Context context, String url, ImageView imageView) {
        Glide.with(context).applyDefaultRequestOptions(RequestOptions.skipMemoryCacheOf(false)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).error(R.mipmap.img_error)
                .placeholder(R.mipmap.img_place)).load(Uri.parse(url)).into(imageView);
    }

    public static void loadImg(Context context, String url, ImageView imageView, RequestOptions
            requestOptions) {
        Glide.with(context).applyDefaultRequestOptions(requestOptions.skipMemoryCacheOf(false)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).error(R.mipmap.img_error)
                .placeholder(R.mipmap.img_place)).load(Uri.parse(url)).into(imageView);
    }

    public static void loadImgByFile(Context context, File file, ImageView imageView) {
        Glide.with(context).applyDefaultRequestOptions(RequestOptions.skipMemoryCacheOf(false)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).error(R.mipmap.img_error)
                .placeholder(R.mipmap.img_place)).load(Uri.fromFile(file)).into(imageView);
    }

    public static void loadImgByFile(Context context, File file, ImageView imageView,
                                     RequestOptions requestOptions) {
        Glide.with(context).applyDefaultRequestOptions(requestOptions.skipMemoryCacheOf(false)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).error(R.mipmap.img_error)
                .placeholder(R.mipmap.img_place)).load(Uri.fromFile(file)).into(imageView);
    }

    public static void loadImgByRes(Context context, int resId, ImageView imageView) {
        Glide.with(context).applyDefaultRequestOptions(RequestOptions.skipMemoryCacheOf(false)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).error(R.mipmap.img_error)
                .placeholder(R.mipmap.img_place)).load(resId).into(imageView);
    }

    public static void loadImgByRes(Context context, int resId, ImageView imageView,
                                    RequestOptions requestOptions) {
        Glide.with(context).applyDefaultRequestOptions(requestOptions.skipMemoryCacheOf(false)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).error(R.mipmap.img_error)
                .placeholder(R.mipmap.img_place)).load(resId).into(imageView);
    }

    public static void parseCookie(Context context, String cookie) {
        if (TextUtils.isEmpty(cookie)) {
            return;
        }
        String[] allCookie = cookie.split(";");
        for (String cookieItem : allCookie) {
            if (cookieItem.contains("visitor.user.name=meiyueJY=")) {
                String accout = cookieItem.split("visitor.user.name=meiyueJY=")[1].trim();
                SPUtils.put(context.getApplicationContext(), Constants.SP_KEY_USER_ACCOUNT, accout);
                JPushInterface.getAlias(context.getApplicationContext(), TagAliasOperatorHelper
                        .ACTION_GET);//查询别名查询不到在添加
                JPushInterface.setMobileNumber(context.getApplicationContext(), TagAliasOperatorHelper
                        .ACTION_ADD, accout);//添加手机号
            } else if (cookieItem.contains("visitor.user.pwd=meiyueJY=")) {
                String password = cookieItem.split("visitor.user.pwd=meiyueJY=")[1].trim();
                SPUtils.put(context.getApplicationContext(), Constants.SP_KEY_USER_PASSWORD,
                        password);
            } else if (cookieItem.contains("visitor.user.token=meiyueJY=")) {
                String token = cookieItem.split("visitor.user.token=meiyueJY=")[1].trim();
                SPUtils.put(context.getApplicationContext(), Constants.SP_KEY_USER_TOKEN, token);
            }

        }
    }
}
